<template>
  <div>
    <el-dialog
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :append-to-body="true"
      title="选择商品"
      width="850px"
      @close="close"
    >
      <div v-loading="loading">
          <div class="filter-container">
            <el-form
              ref="filterForm"
              :model="orderForm"
              label-width="100px"
              size="small"
            >
              <el-row>
                <el-col :span="12">
                  <el-form-item prop="name" label="商品名称：">
                    <el-input v-model="orderForm.name" />
                  </el-form-item>
                   <el-form-item prop="proClass" label="商品分类">
                    <el-select v-model="orderForm.proClass" placeholder="请选择">
                      <el-option
                        v-for="(item, key) in classList"
                        :key="key"
                        :label="item.name"
                        :value="item.id"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item prop="name" label="商品类型：">
                    <el-select v-model="orderForm.proName" placeholder="请选择">
                      <el-option label="主商品" value="MAIN" />
                      <!-- <el-option v-for="(item,key) in goodsTypeOptions" :key="key" :label="item" :value="key" /> -->
                    </el-select>
                  </el-form-item>
                  <el-form-item prop="categoryId" label="门店">
                    <el-select v-model="orderForm.shopId" placeholder="请选择">
                      <el-option
                        v-for="(item, key) in shopList"
                        :key="key"
                        :label="item.name"
                        :value="item.id"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-form-item>
                <el-button type="primary" round @click="search"
                  >查 询</el-button
                >
                <el-button round @click="reset">重 置</el-button>
              </el-form-item>
            </el-form>
          </div>
          <!-- filter end -->

          <!-- table start -->
          <!-- 新增服务 -->

          <div class="table-container">
            <el-table
              :data="orderList"
              border
              stripe
              style="width: 100%"
              size="small"
              element-loading-text="加载中"
              empty-text="暂无数据"
            >
              <el-table-column prop="name" label="商品标题" />
              <el-table-column prop="defaulted" label="商品类型" width="100">
                <template slot-scope="scope">
                  主商品
                </template>
              </el-table-column>
              <el-table-column prop="classifyName" label="商品类目">
                <template slot-scope="scope">
                  <span>
                    {{scope.row.classifyName?scope.row.classifyName:'无'}}
                  </span>
                </template>
              </el-table-column>
              <el-table-column label="选择" width="100">
                <template slot-scope="scope">
                  <!-- <el-radio
                  v-model="form.goodsId"
                  :label="scope.row.goodsId"
                  @change="chooseGoods(scope.row)"
                >选择</el-radio>-->
                  <!--  <el-button :disabled="hasCheckedIds.includes(scope.row.goodsId)" type="text" @click="chooseGoods(scope.row)">
                  {{ hasCheckedIds.includes(scope.row.goodsId) ? '已选择' : '选择' }}
                </el-button>-->
                  <el-checkbox
                    v-model="checkedIds"
                    :disabled="originalCheckedIds.includes(scope.row.goodsId)"
                    :label="scope.row.goodsId"
                    @change="(val) => checkboxChange(val, scope.row)"
                  >
                    {{
                      checkedIds.includes(scope.row.goodsId) ? "已选" : "选择"
                    }}
                  </el-checkbox>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页 -->
            <pagination-direction
              v-if="paginationConfig.total !== 0"
              :config="paginationConfig"
              @sizeschange="sizesChange"
              @pagechange="pageChange"
            />
          </div>
        <!-- table end -->
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button
          :disabled="loading || checkedList.length === 0"
          size="small"
          round
          type="primary"
          @click="submit"
        >
          确定<span>（ 已选 {{ checkedList.length }} ）</span></el-button
        >
        <el-button :disabled="loading" size="small" round @click="cancel"
          >取消</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { productList } from "@/views/wxaMallModule/api/product";
import { categoryTree } from "@/views/wxaMallModule/api/category";
import { getAllShop } from "@/api/shop";
import { mapGetters } from "vuex";
import {
  getGoodsList,
  updateGoodsStatus,
  getClassifyList
} from '@/views/wcyModule/api/product'

export default {
  data() {
    return {
      // 配置
      resolve: null,
      reject: null,
      goodsTypeOptions: {
        100: '实物商品',
        // 101: '配件商品',
        200: '卡/券包'
        // 300: "同城配送",
      },
      goodsDeliveryOptions: {
        // 1: "canExpress",
        2: '同城配送',
        3: '到店自提'
        // 3: "券包",
        // 300: "同城配送",
      },
      statusOptions: {
        0: '已下架',
        1: '已上架'
      },
      categoryTreeOptions: [],
      // 分页配置
      paginationConfig: {
        direction: 'center', // 分页位置
        layout: 'total, sizes, prev, pager, next, jumper', // 分页类型
        pageSizes: [10, 20], // 分页pages
        total: 0,
        page: 1, // 页数-默认1
        pageSize: 10 // 每页条数-默认10
      },
      // 状态
      dialogVisible: null,
      loading: false,
      // 数据
      value: '',
      filterForm: {
        goodsType: 'all',
        barCode: '',
        brandId: '',
        categoryId: [0],
        goodsSerial: '',
        goodsNo: '',
        status: 1,
        title: ''
        // goodsDelivery: "2",
      },

      form: {
        goodsId: null
      },
      originalCheckedIds: [],
      checkedIds: [],
      checkedList: [],
      list: [],
      // 扫码点单相关业务
      // 门店列表
      shopList: [],
      // 分类列表
      classList: [],
      // 业务类型
      //
      orderForm: {
        name: '',
        proName: 'MAIN',
        proClass: '',
        shopId: ''
      },
      orderList: []
    }
  },
  computed: {
    ...mapGetters(['activePageForm'])
  },
  watch: {
    'orderForm.shopId'(val) {
      if (val) this.getProClass()
    }
  },
  created() {},
  mounted() {},

  methods: {
    /**
     * 弹框相关
     */
    open({ hasCheckedIds = [] }) {
      this.originalCheckedIds = hasCheckedIds
      this.checkedIds = hasCheckedIds
      this.fetchData()
      this.getCategoryOptions()
      this.show()
      this.setbusinessType()
      return new Promise((resolve, reject) => {
        this.resolve = resolve
        this.reject = reject
      })
    },

    show() {
      this.dialogVisible = true
    },

    close() {
      this.loading = false
      Object.assign(this.$data, this.$options.data())
      this.originalCheckedIds = []
      this.checkedIds = []
      this.checkedList = []
      this.list = []
      this.form = {
        goodsId: null
      }
    },

    hide() {
      this.resolve = null
      this.reject = null
      this.dialogVisible = false
    },

    /**
     * 数据组
     */
    fetchData(
      pageNum = this.paginationConfig.page,
      pageSize = this.paginationConfig.pageSize
    ) {
      // 加入page
      this.filterForm.pageNum = pageNum
      this.filterForm.pageSize = pageSize
      const params = Object.assign({}, this.filterForm)
      if (
        params.categoryId.length === 0 ||
        (params.categoryId.length === 1 && params.categoryId[0] === 0)
      ) {
        params.categoryId = ''
      } else {
        params.categoryId = params.categoryId[params.categoryId.length - 1]
      }
      if (params.goodsType === 'all') params.goodsTypes = [100, 200]
      // 清除多余字段
      for (const key in params) {
        if (params[key] === '' || params[key] === 'all') {
          delete params[key]
        }
      }
      this.loading = true
      productList(params)
        .then((res) => {
          this.list = res.data.list
          this.paginationConfig.total = res.data.total
          this.paginationConfig.page = res.data.pageNum
        })
        .finally(() => {
          this.filterForm.goodsSerial = null
          this.loading = false
        })
    },

    // 分页sizes改变
    sizesChange() {
      this.getOrderList()
    },

    // 分页page改变
    pageChange() {
      this.getOrderList()
    },

    // 获取类目tree
    getCategoryOptions() {
      return new Promise((resolve, reject) => {
        categoryTree()
          .then((res) => {
            this.categoryTreeOptions = [
              {
                categoryNo: '',
                children: undefined,
                id: 0,
                parentId: 0,
                ranking: 0,
                title: '全部'
              }
            ].concat(this.formatTreeData(res.data))
          })
          .catch((err) => {})
          .finally(() => {})
      })
    },

    // 递归children设置空
    formatTreeData(data) {
      for (var i = 0; i < data.length; i++) {
        if (data[i].children.length < 1) {
          data[i].children = undefined
        } else {
          this.formatTreeData(data[i].children)
        }
      }
      return data
    },

    /**
     * 按钮组
     */
    // 查询
    search() {
      this.getOrderList()
    },

    // 重置
    reset() {
      this.$refs.filterForm.resetFields()
      this.setbusinessType()
    },

    // 保存
    submit() {
      if (this.checkedList.length) { this.resolve && this.resolve(this.checkedList) }
      this.hide()
    },

    // 取消
    cancel() {
      this.hide()
    },

    // 选择
    // chooseGoods(row) {
    //   const params = {
    //     goodsId: row.goodsId,
    //     coverImg: row.coverImg,
    //     title: row.title,
    //     subTitles: row.subTitle,
    //     category: row.categoryName
    //   }
    //   this.resolve && this.resolve(params)
    //   this.hide()
    // },

    /*
     * 状态组
     * */
    // 多选
    checkboxChange(val, row) {
      if (val) {
        let params = {}
        const { name, goodsId, image, classifyName, classifyId } = row
        params = {
          shopId: this.orderForm.shopId,
          title: name,
          goodsId,
          coverImg: image,
          classify: classifyName,
          classifyId
        }
        this.checkedList.push(params)
      } else {
        this.checkedList.splice(this.checkedList.findIndex((item) => item.couponId === row.id), 1)
      }
    },
    // 扫码点单相关逻辑
    // 获取所有门店列表
    async getShopList() {
      await getAllShop({}).then((res) => {
        this.shopList = res.data
        this.orderForm.shopId = res.data[0].id
      })
    },
    // 根据门店id获取商品分类
    async getProClass() {
      const { shopId } = this.orderForm
      await getClassifyList({ shopId, pageNum: 1, pageSize: 999 })
        .then((res) => {
          console.log(res.data.total > 0)
          if (res.data.total > 0) {
            this.classList = res.data.row
            this.orderForm.proClass = res.data.row[0].id
          } else {
            this.classList = [{ name: '无', id: '' }]
            this.orderForm.proClass = ''
          }
        })
    },
    async getOrderList() {
      const { orderForm: { proClass, shopId, name }, paginationConfig: { pageSize, page } } = this
      const params = {
        classifyId: proClass,
        shopId,
        pageSize,
        page,
        name,
        status: 1
      }
      await getGoodsList(params).then(res => {
        this.orderList = res.data.row
        this.paginationConfig.total = res.data.total
        this.paginationConfig.page = res.data.pageNum
      })
    },
    async setbusinessType() {
      await this.getShopList()
      await this.getProClass()
      await this.getOrderList()
    }
    /**
     * 方法组
     */
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
</style>
